package com.luo.storage.interceptor;

import com.luo.storage.utils.JwtTool;
import com.luo.storage.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTool jwtTool;

    @Autowired
    private UserContext userContext;
    /**
     * 拦截
     * 解析令牌，放行登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
            userContext.setUserId(userId);

        }catch (Exception e){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            try (PrintWriter writer = response.getWriter()) {
                writer.write("{\"msg\":\"请先登录!\"}");
                writer.flush();
            } catch (IOException ioException) {
                // 处理写入异常
                ioException.printStackTrace();
            }
            return false;
        }
        return true;
    }
}
